<?php

namespace App\Http\Controllers\system;

use App\Http\Controllers\Controller;
use App\Models\admin\AdminPermissionModel;
use Illuminate\Http\Request;
use lxs\api\ApiResponse;
use lxs\tools\Tools;

class PermissionController extends Controller
{
    public function index(Request $request)
    {
        $data = AdminPermissionModel::orderBy('sort', 'asc')
            ->orderBy('id', 'asc')
            ->get();
        //生成多级权限列表
        $data = $data->toArray();
        $data = Tools::getTree($data);
        return ApiResponse::success($data);
    }

    public function read(Request $request)
    {
        $id = $request->input('id');
        $permission = AdminPermissionModel::findOrFail($id);
        return ApiResponse::success($permission);
    }

    public function add(Request $request)
    {
        $data = $request->validate([
            'pid'  => 'required|int',
            'code' => 'required|string',
            'name' => 'required|string',
            'sort' => 'int'
        ]);
        $data['sort'] = $data['sort'] ?? 0;
        if (AdminPermissionModel::where('code', $data['code'])->exists()) {
            return ApiResponse::error('权限代码已存在');
        }
        $permission = AdminPermissionModel::create([
            'pid'  => $data['pid'],
            'code' => $data['code'],
            'name' => $data['name'],
            'sort' => $data['sort']
        ]);
        if (!$permission) {
            return ApiResponse::error('添加失败');
        }
        return ApiResponse::success('添加成功');
    }

    public function update(Request $request)
    {
        $data = $request->validate([
            'pid'  => 'required|int',
            'code' => 'required|string',
            'name' => 'required|string',
            'sort' => 'int'
        ]);
        $id = $request->input('id');
        //查看是否重复
        if (AdminPermissionModel::where('code', $data['code'])->where('id', '!=', $id)->exists()) {
            return ApiResponse::error('权限代码已存在');
        }
        $permission = AdminPermissionModel::findOrFail($id);
        $permission->pid = $data['pid'];
        $permission->code = $data['code'];
        $permission->name = $data['name'];
        $permission->sort = $data['sort'] ?? $permission->sort;
        if (!$permission->save()) {
            return ApiResponse::error('修改失败');
        }
        return ApiResponse::success('修改成功');
    }

    public function delete(Request $request)
    {
        $id = $request->input('id');
        $permission = AdminPermissionModel::findOrFail($id);
        if (AdminPermissionModel::where('pid', $id)->exists()) {
            return ApiResponse::error('请先删除子权限');
        }
        if (!$permission->delete()) {
            return ApiResponse::error('删除失败');
        }
        return ApiResponse::success('删除成功');
    }
}
